我們可以將 同步(Sync)
與 非同步(Async)
理解為:
JavaScript的 同步
程式碼:
console.log('Sync Begin.');
for (let number = 1; number <= 10; number++) {
console.log('number:', number);
}
console.log('Sync End.');
輸出結果:
Sync Begin.
number: 1
number: 2
number: 3
number: 4
number: 5
number: 6
number: 7
number: 8
number: 9
number: 10
Sync End.
當程式碼為同步時,就是一件事、一件事的做,因此執行順序為:
Sync Begin.
for
迴圈,執行迴圈內程式:
1
2
3
4
5
6
7
8
9
10
Sync End.
JavaScript的 非同步
程式碼:
console.log('Async Begin.');
setTimeout(function() {
console.log('finish.');
}, 1000);
console.log('Async End.');
輸出結果:
Async Begin.
Async End.
finish.
程式碼中有非同步程式碼時,可以同時做好幾件事情,此程式的執行順序為:
Async Begin.
setTimeout
定時 1000毫秒後
顯示 finish.
Async End.
finish.
完整程式碼:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript-Sync and Async</title>
</head>
<body>
<script>
// 同步(Sync)程式碼:
console.log('Sync Begin.');
for (let number = 1; number <= 10; number++) {
console.log('number:', number);
}
console.log('Sync End.');
console.log('------------');
// 非同步(Async)程式碼:
console.log('Async Begin.');
setTimeout(function() {
console.log('finish.');
}, 1000);
console.log('Async End.');
</script>
</body>
</html>
輸出結果:
Sync Begin.
number: 1
number: 2
number: 3
number: 4
number: 5
number: 6
number: 7
number: 8
number: 9
number: 10
Sync End.
------------
Async Begin.
Async End.
finish.